#include "gradient_interpolator.h"

#include <cassert>

namespace util {
  //
  // Gradient_interpolator
  //

  GradientInterpolator::GradientInterpolator(const QGradientStops &Stops_)
  : mStops(Stops_)
  {
  }

  QColor GradientInterpolator::operator()(qreal Value_) const
  {
    QColor col = Qt::white;
    assert(Value_ >= 0.0 && Value_ <= 1.0);

    for (size_t i = 1; i < mStops.size(); ++i)
    {
      const QGradientStop &curStop  = mStops[i];
      const QGradientStop &prevStop = mStops[i-1];

      if (curStop.first >= Value_)
      {
        const qreal coeff = (curStop.first - Value_) / (curStop.first - prevStop.first);
        const QColor &curColor  = curStop.second;
        const QColor &prevColor = prevStop.second;

        col.setRedF(curColor.redF() * (1 - coeff) + prevColor.redF() * coeff);
        col.setGreenF(curColor.greenF() * (1 - coeff) + prevColor.greenF() * coeff);
        col.setBlueF(curColor.blueF() * (1 - coeff) + prevColor.blueF() * coeff);
        break;
      }

    }
    return col;
  }
} // namespace util